;$(document).ready(function(){
	
	// 场景
	var scene;
	// 渲染器对象
	var renderer;
	//创建相机对象
	var camera;
	// 鼠标对象
	var mouse;
	// 射线
	var raycaster;
	// 方块组
	var boxGroup;
	var currentBox;
	
	// 创建线条
	function createLine (a,b,col1,col2) {
		// a，b端点坐标,col1端点1颜色，col2端点2颜色
		var geometry = new THREE.Geometry();//声明一个空几何体对象
	    var p1 = new THREE.Vector3(a[0],a[1],a[2]);//顶点1坐标
	    var p2 = new THREE.Vector3(b[0],b[1],b[2]);//顶点2坐标
	    geometry.vertices.push(p1,p2); //顶点坐标添加到geometry对象
	    
	    var color1 = new THREE.Color(col1);//顶点1颜色——红色
    	var color2 = (typeof col2 == 'number') ? new THREE.Color(col2) : color1;//顶点3颜色——蓝色 
    	geometry.colors.push(color1, color2);//顶点颜色传入几何体对象
    	
	    var material=new THREE.LineBasicMaterial({
	        vertexColors: THREE.VertexColors,//以顶点颜色为准
	    });//材质对象
	    return new THREE.Line(geometry,material);//线条模型对象
	}
	
	// 创建立方体
	function createBoxGeometry(s,p,c) {
		// s大小（长宽高），p位置，c颜色
		var box=new THREE.BoxGeometry(s[0],s[1],s[2]);//创建一个立方体几何对象
		var material = new THREE.MeshLambertMaterial({color:c}); //材质对象
		var mesh= new THREE.Mesh(box,material);//网格模型对象
		mesh.translateX(p[0]);
	    mesh.translateY(p[1]);
	    mesh.translateZ(p[2]);
		return mesh;
	}
	
	// 创建魔方，r长宽高，pos中心点坐标,n阶数
	function createCubeBox(r,pos,n) {
		var len = r * (n-2); // 最远距离
		var group = new THREE.Group()
		for (var x = pos[0] - len; x <= pos[0] + len; x+=r) {
			for (var y = pos[1] - len; y <= pos[1] + len; y+=r) {
				for (var z = pos[2] - len; z <= pos[2] + len; z+=r) {
					var temp = createBoxGeometry([r,r,r],[x,y,z], Math.random() * 0xffffff);
					group.add(temp);
				}
			}
		}
		return group;
	}
	
	function animate() {
		requestAnimationFrame( animate );
		render();
	}
	
	// 渲染
	function render() {
        renderer.render(scene,camera);//执行渲染操作
    }
	
	function init() {
		
		// 初始化场景
		scene = new THREE.Scene();
		mouse =  new THREE.Vector2();
		raycaster = new THREE.Raycaster();
		
		// 光源设置
		var point=new THREE.PointLight(0xffffff); 
		point.position.set(400,200,300);//点光源位置
		scene.add(point);//点光源添加到场景中
		//环境光
		var ambient=new THREE.AmbientLight(0x444444);
		scene.add(ambient);
		
		// 相机设置
		var width = window.innerWidth;//窗口宽度
		var height = window.innerHeight;//窗口高度
		var k = width/height;//窗口宽高比
		var s = 130;//三维场景缩放系数
		camera=new THREE.OrthographicCamera(-s*k,s*k, s,-s,1,1000);
		camera.position.set(400,200,400);//设置相机位置
		camera.lookAt(scene.position);//设置相机方向(指向的场景对象)
		
		// 渲染器设置
		renderer=new THREE.WebGLRenderer();
		renderer.setSize(width,height);
		renderer.setClearColor(0xfcfcfc,1);//设置背景颜色
		document.body.appendChild(renderer.domElement);//body元素中插入canvas对象
		
	    var controls = new THREE.OrbitControls(camera);//创建控件对象
		controls.addEventListener('change', render);//监听鼠标、键盘事件
		
		// 创建线条对象
	    var line1 = createLine([-500,0,0],[500,0,0],0x0000ff);
	    var line2 = createLine([0,-500,0],[0,500,0],0x00ff00);
	    var line3 = createLine([0,0,-500],[0,0,500],0xff0000);
	    scene.add(line1,line2,line3);//线条对象添加到场景中
	    
	    // 创建立方体
		boxGroup = createCubeBox(20, [0,0,0], 3);
		scene.add(boxGroup); //网格模型添加到场景中
	    
	    initBind();
	    
	    //执行渲染操作
		animate();
		
	}
	
	// 根据向量判断方向
	function getDirection(sub) {
		var direction;
        //判断差向量和x、y、z轴的夹角
        var xAngle = vector3.angleTo(xLine);
        var xAngleAd = vector3.angleTo(xLineAd);
        var yAngle = vector3.angleTo(yLine);
        var yAngleAd = vector3.angleTo(yLineAd);
        var zAngle = vector3.angleTo(zLine);
        var zAngleAd = vector3.angleTo(zLineAd);
        var minAngle = min([xAngle,xAngleAd,yAngle,yAngleAd,zAngle,zAngleAd]);//最小夹角

        switch(minAngle){
            case xAngle:
                direction = 0;//向x轴正方向旋转90度（还要区分是绕z轴还是绕y轴）
                if(normalize.equals(yLine)){
                    direction = direction+0.1;//绕z轴顺时针
                }else if(normalize.equals(yLineAd)){
                    direction = direction+0.2;//绕z轴逆时针
                }else if(normalize.equals(zLine)){
                    direction = direction+0.3;//绕y轴逆时针
                }else{
                    direction = direction+0.4;//绕y轴顺时针
                }
                break;
            case xAngleAd:
                direction = 1;//向x轴反方向旋转90度
                if(normalize.equals(yLine)){
                    direction = direction+0.1;//绕z轴逆时针
                }else if(normalize.equals(yLineAd)){
                    direction = direction+0.2;//绕z轴顺时针
                }else if(normalize.equals(zLine)){
                    direction = direction+0.3;//绕y轴顺时针
                }else{
                    direction = direction+0.4;//绕y轴逆时针
                }
                break;
            case yAngle:
                direction = 2;//向y轴正方向旋转90度
                if(normalize.equals(zLine)){
                    direction = direction+0.1;//绕x轴逆时针
                }else if(normalize.equals(zLineAd)){
                    direction = direction+0.2;//绕x轴顺时针
                }else if(normalize.equals(xLine)){
                    direction = direction+0.3;//绕z轴逆时针
                }else{
                    direction = direction+0.4;//绕z轴顺时针
                }
                break;
            case yAngleAd:
                direction = 3;//向y轴反方向旋转90度
                if(normalize.equals(zLine)){
                    direction = direction+0.1;//绕x轴顺时针
                }else if(normalize.equals(zLineAd)){
                    direction = direction+0.2;//绕x轴逆时针
                }else if(normalize.equals(xLine)){
                    direction = direction+0.3;//绕z轴顺时针
                }else{
                    direction = direction+0.4;//绕z轴逆时针
                }
                break;
            case zAngle:
                direction = 4;//向z轴正方向旋转90度
                if(normalize.equals(yLine)){
                    direction = direction+0.1;//绕x轴顺时针
                }else if(normalize.equals(yLineAd)){
                    direction = direction+0.2;//绕x轴逆时针
                }else if(normalize.equals(xLine)){
                    direction = direction+0.3;//绕y轴顺时针
                }else{
                    direction = direction+0.4;//绕y轴逆时针
                }
                break;
            case zAngleAd:
                direction = 5;//向z轴反方向旋转90度
                if(normalize.equals(yLine)){
                    direction = direction+0.1;//绕x轴逆时针
                }else if(normalize.equals(yLineAd)){
                    direction = direction+0.2;//绕x轴顺时针
                }else if(normalize.equals(xLine)){
                    direction = direction+0.3;//绕y轴逆时针
                }else{
                    direction = direction+0.4;//绕y轴顺时针
                }
                break;
            default:
                break;
        }
        return direction;
	}
	
	// 鼠标按下事件
	function mousedown(event) {
		event.preventDefault();
		mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
		mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;
		var intersects = raycaster.intersectObjects( boxGroup.children );
		if (intersects.length) {
			currentBox = intersects[ 0 ];
		}
	}
	
	// 鼠标移动
	function mousemove(event) {
		event.preventDefault();
		mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
		mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;
		var intersects = raycaster.intersectObjects( boxGroup.children );
		if (intersects.length) {
			var moveBox = intersects[ 0 ];
			if (!currentBox.point.equals(moveBox.point)) {
				var sub = moveBox.sub(currentBox);
				var direction = getDirection(sub);
			}
			
			controls.enabled = false;
		} else {
			controls.enabled = true;
		}
	}
	
	// 绑定事件
	function initBind() {
		document.addEventListener('mousedown', mousedown, false);
		document.addEventListener('mousemove', mousemove, false);
	}
	
	init();
	
	//https://juejin.im/entry/58c0cb452f301e006ba6d7ae
	
});
